package controller;

import java.io.IOException;
import java.lang.reflect.Constructor;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class Controller extends HttpServlet {
	
	public synchronized void init() throws ServletException {
    //TODO add dao here
	String test="";
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		process(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		process(request, response);
	}

	private void process(HttpServletRequest request,
			HttpServletResponse response) {
		String path = request.getServletPath();
        String actionName=getActionName(path);
        String nextPage=null;
        Action action=null;
        Class actionClass;
		try {
			actionClass = Class.forName("controller."+actionName+"Action");
			Constructor<? extends Action> actionConstructor = actionClass.getDeclaredConstructor();
			Object arglist[] = {};
			action = (Action)actionConstructor.newInstance(arglist);
		
		} catch (Exception e) {
			nextPage="Home.do";
			nextPage(request,response,nextPage);
			return;
		}
		nextPage=action.perform(request, response);
		if(!response.isCommitted()) {
		nextPage(request,response,nextPage);
		}
	}
	private String getActionName(String path){
		int slash = path.lastIndexOf('/');
		int dot=path.indexOf(".", slash+1);
		return path.substring(slash + 1,dot);
	}
	private void nextPage(HttpServletRequest request, HttpServletResponse response, String nextPage){
		String path="Home.do";
		if(nextPage!=null&&nextPage.contains(".do")){
			path=nextPage;
		}
		else if(nextPage!=null&&nextPage.contains(".view")){
			path="WEB-INF/view/"+nextPage.replace(".view", ".jsp");
		}
		
		RequestDispatcher dispatch = request.getRequestDispatcher(path);
		try {
			dispatch.forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
